﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using Project.Domain.AggregateModels;
using Project.Domain.Seedwork;
using Project.Infrastructure.Models.Mapping;
using System.Threading;
using System.Threading.Tasks;
using ProjectEntity = Project.Domain.AggregateModels.Project;

namespace Project.Infrastructure.Models
{
    public class ProjectContext
        : DbContext, IUnitOfWork
    {
        private readonly IMediator _mediator;
        public ProjectContext(DbContextOptions<ProjectContext> options,
            IMediator mediator)
            : base(options)
        {
            _mediator = mediator;
        }

        public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            await _mediator.DispatchDomainEventsAsync(this);
            await base.SaveChangesAsync();
            return true;
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfiguration(new ProjectMap());
            modelBuilder.ApplyConfiguration(new BPFileMap());
            modelBuilder.ApplyConfiguration(new ProjectContributorMap());
            modelBuilder.ApplyConfiguration(new ProjectViewerMap());
            modelBuilder.ApplyConfiguration(new ProjectVisibleRuleMap());
            modelBuilder.ApplyConfiguration(new ProjectPropertyMap());
            modelBuilder.ApplyConfiguration(new BelongToMap());

            base.OnModelCreating(modelBuilder);
        }

        public virtual DbSet<ProjectEntity> Project { get; set; }
        public virtual DbSet<BPFile> BPFile { get; set; }
        public virtual DbSet<ProjectContributor> ProjectContributor { get; set; }
        public virtual DbSet<ProjectViewer> ProjectViewer { get; set; }
        public virtual DbSet<ProjectVisibleRule> ProjectVisibleRule { get; set; }
        public virtual DbSet<ProjectProperty> ProjectProperty { get; set; }
        public virtual DbSet<BelongTo> BelongTo { get; set; }
    }
}
